<template>
  <div class="login">
    <p class="login-title"><span class="icon"></span> 欢迎使用 AI Storage</p>
    <div class="login-img"></div>
    <div v-if="idOrPsw" class="login-id">
      <P style="text-align: center; font-size: 15px;margin-bottom: 20px;">登录我的Storage</P>

      <p>设备ID</p>
      <van-form @submit="onSubmitID">
        <van-field class="input" :rules="[{ required: true, message: '请填写设备ID' }]" v-model="id" placeholder="请输入设备ID" />
        <van-button class="button" :disabled="buttonDisabled" type="primary" native-type="submit"> {{ networkingbutton
          }}</van-button>
      </van-form>
    </div>
    <div v-else class="login-password">
      <P style="text-align: center; font-size: 15px;margin-bottom: 20px; font-weight: 600;">登录我的Storage</P>

      <p>当前设备ID</p>
      <p>{{ port.device_id }}</p>
      <van-form @submit="onSubmitPassword">
        <van-field class="input" label-align="top" type="password" label="登录密码"
          :rules="[{ required: true, message: '请填写设备登录密码' }]" v-model="password" placeholder="请填写设备登录密码" />
        <div class="button">
          <van-button @click="idOrPsw = true"> 取消</van-button>
          <van-button type="primary" native-type="submit">确定 </van-button>
        </div>
      </van-form>
      <van-overlay :show="loading">
        <van-loading color="#1989fa" size="24"
          style="position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);">
          登录中...
        </van-loading>
      </van-overlay>
    </div>
        <iframe v-if="showIframe" ref="myIframe" style="display: none;" id="myIframe" :src="frameUrl" width="100%" height="100%"> </iframe>
<!--        <iframe v-if="showIframe" ref="myIframe" style="display: none;" id="myIframe" src="http://ts.aipocket-nas.igrsservice.com/#/" width="100%" height="100%"> </iframe>-->
<!--    <iframe v-if="showIframe" ref="myIframe" style="display: none;" id="myIframe" src="http://localhost:8080/#/" width="100%" height="100%"> </iframe>-->
  </div>
  <van-notify type="success">
    <van-icon name="bell" style="margin-right: 4px;" />
    <span>登录失败</span>
  </van-notify>
</template>


<script setup>
import {ref, nextTick, onMounted, computed} from "vue"
import { useRouter, useRoute } from "vue-router";
import {login, nasLogin, testNetwork} from "@/api/index";
import { storeToRefs } from 'pinia'
import { showNotify } from 'vant'
import { usePortStore } from '@/stores/index'
const router = useRouter()
const route = useRoute()
const myIframe = ref(null)
const id = ref("")
const password = ref("")
const showIframe = ref(false)
const flag = ref(false)
const show = ref(false)
//通过设备id连接 点击确定时为验证中...
const networkingbutton = ref('确定')
//下一步按钮是否禁用
const buttonDisabled = ref(false)
const idOrPsw = ref(true)
const loading = ref(false)
const networkIp = ref('')
const { setPort,setUrl,afterURL} = usePortStore()
const { port ,} = storeToRefs(usePortStore())
const frameUrl = computed(()=>{
  return "http://" + usePortStore().afterURL + ":91";
})


onMounted(async ()=>{
  const host = route.query.host
  const pocket = route.query.pocket
  if(host !== undefined){
    networkIp.value = host
    frameUrl.value = "http://" + host + ":91";
    setUrl(host)
    if(pocket != undefined){
      id.value = pocket
      onSubmitID()
    }
  }
})
const onSubmitID = async () => {
  networkingbutton.value = '验证中，请稍后'
  buttonDisabled.value = true
  loading.value = true
  if(networkIp.value.includes("192.168.150.1")){
    setPort({ device_id:id.value,port:8000, time: new Date().getTime() })
    idOrPsw.value = false
    showIframe.value = true
    networkingbutton.value = '确认'
    buttonDisabled.value = false
    loading.value = false
  }else {

    try {
      const data = await login({deviceId: id.value})
      if (data.code === 0) {
        setTimeout(() => {
          loading.value = false
        }, 500);
        setPort({...data.data, time: new Date().getTime()})
        if (data.data.wireless !== null && data.data.wireless.length > 0) {
          console.log(data.data.wireless[0])
          try {
            const response = await testNetwork(data.data.wireless[0])
            if (response.code == 200) {
              // window.location = "http://" + data.data.wireless[0] + ":89/login?host="+data.data.wireless[0] + "&pocket="+id.value
            }
          } catch (e) {
          }
        }
        idOrPsw.value = false
        showIframe.value = true
      } else if (data.code === 1) {
        showNotify({type: 'danger', message: '设备不存在'});
      }
    } catch (error) {
      loading.value = false
      console.log(error)
    } finally {
      networkingbutton.value = '确认'
      buttonDisabled.value = false

    }
  }
}

const onSubmitPassword = async () => {

  loading.value = true
  try {
    const userinfo = await nasLogin({username: port.value.device_id, password: port.value.device_id})
    if (userinfo.success === 200) {
      setPort({...port.value, userinfo: userinfo.data})
      userinfo.port = port.value.port
      userinfo.netWork = networkIp.value
      console.log(userinfo)
      myIframe.value.contentWindow.postMessage({...userinfo, message: 'login'}, '*');
      loading.value = false
      router.push(route.redirectedFrom?.path ?? "/")
    } else {
      loading.value = false
    }
  } catch (e) {
    console.log(e)
    showNotify({ type: 'danger', message: '登录失败' });
    loading.value = false
  }

  // router.push('/')
}


</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 24px;

  .login-img {
    width: 100%;
    height: 200px;
    background: url('@/assets/image/设备.png') no-repeat center;
  }

  .login-title {
    color: #000;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    margin-top: 18px;
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      width: 32px;
      height: 32px;
      margin-right: 10px;
      background: url('@/assets/image/发送.png') no-repeat center;
    }
  }

  .login-id {
    width: 351px;
    height: 255px;
    border-radius: 8px;
    // border: 1px solid #B2B2B2;
    background: #FFF;
    // margin-top: 48px;
    padding: 32px;

    p {
      font-size: 14px;
      font-weight: 600;
    }

    .input {
      border-radius: 6px;
      border: 1px solid #E1E2E5;
      background: #FFF;
      height: 40px;
      margin: 24px 0;
      padding-top: 7px;
      overflow: visible;

      :deep(.van-field__error-message) {
        margin-top: 10px;
        margin-left: -14px;
      }

    }

    .button {
      width: 100%;
      height: 36px;
      border-radius: 4px;
    }
  }

  .login-password {
    width: 351px;
    height: 300px;
    border-radius: 8px;
    // border: 1px solid #B2B2B2;
    background: #FFF;
    // margin-top: 48px;
    padding: 32px;

    p {
      &:nth-child(2) {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      &:nth-child(3) {
        color: #686868;
        font-size: 14px;
      }
    }

    .input {
      height: 105px;
      padding-left: 0;
      padding-right: 0;

      :deep(.van-cell__value) {
        height: 65px;

        input {

          height: 40px;
          padding: 0 16px;
          border-radius: 6px;
          border: 1px solid #E1E2E5;
          background: #FFF;
        }
      }

    }

    .button {
      display: flex;
      margin-top: 15px;

      justify-content: space-between;

      :deep(button) {
        width: 133.5px;
        height: 36px;
      }
    }
  }
}
</style>
